/**
 * Created by ren on 29/03/2017.
 */
'use strict';
import React, {Component} from 'react';
import {
  Platform,
  Image,
  View,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  StatusBar,
  Dimensions,
  KeyboardAvoidingView
} from 'react-native'
import * as api from '../utils/api'
import * as NetService from '../utils/netservice'
import {Container, Form, Button, Input} from 'native-base'
import {getSize} from '../utils/response'
import Icon from 'react-native-vector-icons/Ionicons';
import PageUtil from '../utils/PageUtil';
import NavigationDrawer from '../components/NavigationDrawer'
import FindPwd from './FindPwd'
import {cutTab, checkLogin} from '../actions'
import {connect} from 'react-redux'
class Login extends Component {
  constructor(props) {
    super(props);
    this.PageUtil = new PageUtil();
    // 初始状态
    this.state = {
      userName: '',
      password: '',
      checkView: <Icon name="ios-square-outline" size={getSize(20)} color="#95989A"/>,
      loginText: '登录'
    }
  }

  componentDidMount() {
    storage.load({
      key: 'loginData'
    }).then(ret => {
      let userName = ret.userName;
      this.setState({
        userName: userName
      })
    }).catch(err => {
      console.log(err)
    })
  }

  login() {
    const userName = this.state.userName;
    const password = this.state.password
    if (!userName) {
      NetService.toast('用户名不能为空！');
      return
    }
    if (!password){
      NetService.toast('密码不能为空！');
      return
    }
    this.setState({
      buttonStatus: true,
      loginText: '登录中……'
    })
    NetService.post(api.login, {
      userName: userName,
      password: password
    }, {
      isBack: true
    }).then(response => {
      const {dispatch} =this.props;
      dispatch(checkLogin())
      dispatch(cutTab('checkOrder'))
      this.setState({
        buttonStatus: false,
        loginText: '登录'
      })
      storage.save({
        key: 'loginData',   // Note: Do not use underscore("_") in key!
        rawData: {
          userName: userName,
          password: password,
        }
      });
      storage.save({
        key: 'loginState',   // Note: Do not use underscore("_") in key!
        rawData: {
          id: response.id,
          nickName: response.nickName,
          phone: response.phone
        }
      });

      this.PageUtil.resetTo(NavigationDrawer)
    }, () => {
      this.setState({
        buttonStatus: false,
        loginText: '登录'
      })
    }).catch(() => {
      this.setState({
        buttonStatus: false,
        loginText: '登录'
      })
    })
  }

  _onChange(value, flag) {
    if (flag === 'userName') {
      this.setState({
        userName: value
      })
    } else {
      this.setState({
        password: value
      })
    }
  }

  _toFindPwd() {
    this.PageUtil.jumpPageWithComponent(FindPwd)
  }

  render() {
    return (
      <Container style={{flex:1,backgroundColor:'white'}}>
        <StatusBar
          backgroundColor={'#303135'}
        />
        <View
          style={{backgroundColor:'white'}}>
          <Image source={require('../images/login_background.png')}
                 style={{width: Dimensions.get('window').width,height:getSize(196),resizeMode: 'stretch'}}>
            <View style={{justifyContent: 'center',alignItems: 'center',marginTop:30}}>
              <Text style={{fontSize:getSize(19),marginTop:getSize(35),backgroundColor:'rgba(0,0,0,0)',color:'white'}}>万颗商城</Text>
              <Text
                style={{fontSize:getSize(23),marginTop:getSize(5),marginBottom:getSize(35.5),backgroundColor:'rgba(0,0,0,0)',color:'white'}}>供应商接单系统</Text>
            </View>
          </Image>
          <Form style={{marginLeft: getSize(27.5),marginRight: getSize(27.5),marginTop:getSize(20)}}>
            <View style={styles.inputWrap}>
              <Input
                multiline={true}
                placeholder="用户名"
                value={this.state.userName}
                onChangeText={(userName,flag) => this._onChange(userName,'userName')}
                style={_styles.input}
              />
            </View>
            <View style={[styles.inputWrap,{marginTop:getSize(16)}]}>
              <Input
                secureTextEntry={true}
                placeholder="密码"
                onChangeText={(password,flag) => this._onChange(password,'password')}
                value={this.state.password}
                onSubmitEditing={()=>this.login()}
                returnKeyType="go"
                style={_styles.input}
              />
            </View>
            <View style={{flexDirection:'row'}}>
              <View
                style={{flexDirection:'row-reverse',marginTop:getSize(10),marginLeft:getSize(7),flex:1}}>
                <TouchableOpacity onPress={()=>this._toFindPwd()}>
                  <View>
                    <Text style={{marginLeft:getSize(6),fontSize:getSize(15)}}>忘记密码?</Text>
                  </View>
                </TouchableOpacity>
              </View>
            </View>
            <Button
              block
              onPress={()=>this.login()}
              style={{marginLeft:0,marginRight:0,marginTop:getSize(40),borderRadius: getSize(20),height:getSize(39),backgroundColor:'#16BD42'}}
            >
              <Text style={{color:'white',fontSize:getSize(15)}}>{this.state.loginText}</Text>
            </Button>
          </Form>
        </View>
      </Container>
    )
  }
}
export default connect()(Login)
const styles = StyleSheet.create({
  inputWrap: {
    borderWidth: getSize(1 / 3),
    borderColor: '#a5a5a5',
    borderRadius: getSize(20),
    height: getSize(39),
    paddingLeft: getSize(10),
    marginLeft: 0,
    marginRight: 0,
    borderBottomWidth: 0.5,
    paddingTop: Platform.OS === 'ios' ? getSize(5) : 0
  },
  input: {
    padding: 0,
    fontSize: getSize(15),
    height: getSize(39)
  }
})
const _styles = {
  input: {
    padding: 0,
    fontSize: getSize(15),
    height: getSize(39)
  }
}